package com.hwtx.form.assistant;

import com.google.common.collect.Lists;
import com.hwtx.form.domain.FormNotExistException;
import com.hwtx.form.domain.def.FormProperties;
import com.hwtx.form.domain.service.FormService;
import com.hwtx.form.query.FormValueQuery;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.model.ToolContext;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

import static com.hwtx.form.domain.FormConstants.FORM_MANAGE_HANDLE_NAME;

@Slf4j
@Configuration(proxyBeanMethods = false)
public class FromAssistantTools {

    @Resource
    private FormService formService;

    public record FormRequest(String formName, String type, String content) {
    }

    @Tool(description = "创建表单")
    public String createForm(@ToolParam(description = "表单参数，包括表单名称、表单类型、表单内容；其中表单内容为json给是，并且顶层包含meta元素") FormRequest request, ToolContext toolContext) {
        String userName = (String) toolContext.getContext().get("loginName");
        Map<String, Object> params = Map.of("formName", request.formName(),
                "formType", request.type(), "content", request.content(), "type", FORM_MANAGE_HANDLE_NAME);
        try {
            formService.saveFormData(null, params, userName);
        } catch (Exception e) {
            log.error("创建表单失败", e);
            return "创建表单失败";
        }
        return "创建表单成功";
    }

    @Tool(description = "删除表单")
    public String delForm(@ToolParam(description = "表单Id") Long formId, ToolContext toolContext) {
        try {
            FormValueQuery query = new FormValueQuery();
            query.setValueIds(Lists.newArrayList(formId));
            query.setFormId(formId);
            query.setType(FORM_MANAGE_HANDLE_NAME);
            query.setParameters(Map.of("handle", new String[]{"formConfig"}));
            Object ret = formService.remove(query);
            if (ret instanceof Boolean && (Boolean) ret) {
                return "删除表单成功";
            } else {
                return "删除表单失败";
            }
        } catch (FormNotExistException e) {
            return "表单不存在";
        } catch (Exception e) {
            log.error("删除表单", e);
            return "删除表单";
        }
    }

    @Tool(description = "获取表单详情")
    public FormProperties getFormDetail(@ToolParam(description = "表单Id") Long formId, ToolContext toolContext) {
        return formService.getFormDef(formId);
    }
}
